home *** CD-ROM | disk | FTP | other *** search
/ SVM Mac 58 / CD-ROM N°58.iso / navigateurs / Netscape Folder / chrome / navigator / content / default / navigator.js < prev    next >
Encoding:
JavaScript  |  2000-04-19  |  35.7 KB  |  1,146 lines  |  [TEXT/MOSS]

  1. /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  2.  *
  3.  * The contents of this file are subject to the Netscape Public
  4.  * License Version 1.1 (the "License"); you may not use this file
  5.  * except in compliance with the License. You may obtain a copy of
  6.  * the License at http://www.mozilla.org/NPL/
  7.  *
  8.  * Software distributed under the License is distributed on an "AS
  9.  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  10.  * implied. See the License for the specific language governing
  11.  * rights and limitations under the License.
  12.  *
  13.  * The Original Code is mozilla.org code.
  14.  *
  15.  * The Initial Developer of the Original Code is Netscape
  16.  * Communications Corporation.  Portions created by Netscape are
  17.  * Copyright (C) 1998 Netscape Communications Corporation. All
  18.  * Rights Reserved.
  19.  *
  20.  * Contributor(s): 
  21.  */
  22.  
  23. var pref = null;
  24. var bundle = srGetStrBundle("chrome://navigator/locale/navigator.properties");
  25.  
  26. // in case we fail to get the start page, load this
  27. var startPageDefault = "about:blank";
  28.  
  29. // in case we fail to get the home page, load this
  30. var homePageDefault = bundle.GetStringFromName( "homePageDefault" );
  31.  
  32. try {
  33.     pref = Components.classes['component://netscape/preferences'];
  34.     pref = pref.getService();
  35.     pref = pref.QueryInterface(Components.interfaces.nsIPref);
  36. }
  37. catch (ex) {
  38.     dump("failed to get prefs service!\n");
  39.     pref = null;
  40. }
  41.  
  42.   var appCore = null;
  43.   var defaultStatus = bundle.GetStringFromName( "defaultStatus" ); 
  44.   var explicitURL = false;
  45.  
  46.  
  47. function UpdateHistory(event)
  48. {
  49.     // This is registered as a capturing "load" event handler. When a
  50.     // document load completes in the content window, we'll be
  51.     // notified here. This allows us to update the global history and
  52.     // set the document's title information.
  53.  
  54.    //  dump("UpdateHistory: content's location is '" + window.content.location.href + "',\n");
  55.     //dump("                         title is '" + window.content.document.title + "'\n");
  56.  
  57.     if ((window.content.location.href) && (window.content.location.href != ""))
  58.     {
  59.         try
  60.         {
  61.             var history = Components.classes["component://netscape/browser/global-history"].getService();
  62.             if (history) history = history.QueryInterface(Components.interfaces.nsIGlobalHistory);
  63.             if (history) history.SetPageTitle(window.content.location.href, window.content.document.title);
  64.         }
  65.         catch (ex)
  66.         {
  67.             dump("failed to set the page title.\n");
  68.         }
  69.     }
  70. }
  71.  
  72. function savePage( url ) {
  73.         // Default is to save current page.
  74.         if ( !url ) {
  75.             url = window.content.location.href;
  76.         }
  77.         // Use stream xfer component to prompt for destination and save.
  78.         var xfer = Components
  79.                      .classes[ "component://netscape/appshell/component/xfer" ]
  80.                        .getService( Components.interfaces.nsIStreamTransfer );
  81.         try {
  82.             // When Necko lands, we need to receive the real nsIChannel and
  83.             // do SelectFileAndTransferLocation!
  84.  
  85.             // Use this for now...
  86.             xfer.SelectFileAndTransferLocationSpec( url, window );
  87.         } catch( exception ) {
  88.             // Failed (or cancelled), give them another chance.
  89.             dump( "SelectFileAndTransferLocationSpec failed, rv=" + exception + "\n" );
  90.         }
  91.         return;
  92.     }
  93.  
  94.  
  95. function UpdateBookmarksLastVisitedDate(event)
  96. {
  97.     if ((window.content.location.href) && (window.content.location.href != ""))
  98.     {
  99.         try
  100.         {
  101.             // if the URL is bookmarked, update its "Last Visited" date
  102.             var bmks = Components.classes["component://netscape/browser/bookmarks-service"].getService();
  103.             if (bmks)    bmks = bmks.QueryInterface(Components.interfaces.nsIBookmarksService);
  104.             if (bmks)    bmks.UpdateBookmarkLastVisitedDate(window.content.location.href);
  105.         }
  106.         catch(ex)
  107.         {
  108.             dump("failed to update bookmark last visited date.\n");
  109.         }
  110.     }
  111. }
  112.  
  113.  
  114.  
  115. function UpdateInternetSearchResults(event)
  116. {
  117.     if ((window.content.location.href) && (window.content.location.href != ""))
  118.     {
  119.         var    searchInProgressFlag = false;
  120.  
  121.         try
  122.         {
  123.             var search = Components.classes["component://netscape/rdf/datasource?name=internetsearch"].getService();
  124.             if (search)    search = search.QueryInterface(Components.interfaces.nsIInternetSearchService);
  125.             if (search)    searchInProgressFlag = search.FindInternetSearchResults(window.content.location.href);
  126.         }
  127.         catch(ex)
  128.         {
  129.         }
  130.  
  131.         if (searchInProgressFlag == true)
  132.         {
  133.             RevealSearchPanel();
  134.         }
  135.     }
  136. }
  137.  
  138.  
  139.  
  140. function createBrowserInstance()
  141. {
  142.     appCore = Components
  143.                 .classes[ "component://netscape/appshell/component/browser/instance" ]
  144.                   .createInstance( Components.interfaces.nsIBrowserInstance );
  145.     if ( !appCore ) {
  146.         alert( "Error creating browser instance\n" );
  147.     }
  148.   }
  149.  
  150.   function Startup()
  151.   {
  152.     //  TileWindow();
  153.     // Make sure window fits on screen initially
  154.     //FitToScreen();
  155.     
  156.     // Create the browser instance component.
  157.     createBrowserInstance();
  158.     if (appCore == null) {
  159.         // Give up.
  160.         window.close();
  161.     }
  162.  
  163.     // Initialize browser instance..
  164.     appCore.setWebShellWindow(window);
  165.     
  166.     tryToSetContentWindow();
  167.     
  168.     // Add a capturing event listener to the content area
  169.     // (rjc note: not the entire window, otherwise we'll get sidebar pane loads too!)
  170.     //  so we'll be notified when onloads complete.
  171.     var contentArea = document.getElementById("appcontent");
  172.     if (contentArea)
  173.     {
  174.         contentArea.addEventListener("load", UpdateHistory, true);
  175.         contentArea.addEventListener("load", UpdateBookmarksLastVisitedDate, true);
  176.         contentArea.addEventListener("load", UpdateInternetSearchResults, true);
  177.     }
  178.  
  179.      // Check for window.arguments[0].  If present, go to that url.
  180.     if ( window.arguments && window.arguments[0] ) {
  181.         // Load it using yet another psuedo-onload handler.
  182.         onLoadViaOpenDialog();
  183.     }
  184.   }
  185.  
  186. function Shutdown()
  187. {
  188.     try
  189.     {
  190.         // If bookmarks are dirty, flush 'em to disk
  191.         var bmks = Components.classes["component://netscape/browser/bookmarks-service"].getService();
  192.         if (bmks)    bmks = bmks.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
  193.         if (bmks)    bmks.Flush();
  194.     // give history a change at flushing to disk also                           
  195.     var history = getService( "component://netscape/browser/global-history", "nsIRDFRemoteDataSource" );
  196.     if (history)    
  197.       history.Flush();   
  198.     }
  199.     catch (ex)
  200.     {
  201.     }
  202.   // Close the app core.
  203.   if ( appCore )
  204.     appCore.close();
  205. }
  206.  
  207.   function onLoadWithArgs() {
  208.     // See if Startup has been run.
  209.     if ( appCore ) {
  210.         // See if load in progress (loading default page).
  211.         if ( document.getElementById("Browser:Throbber").getAttribute("busy") == "true" ) {
  212.             dump( "Stopping load of default initial page\n" );
  213.             appCore.stop();
  214.         }
  215.         dump( "Loading page specified on ShowWindowWithArgs\n" );
  216.         appCore.loadInitialPage();
  217.     } else {
  218.         // onLoad handler timing is not correct yet.
  219.         dump( "onLoadWithArgs not needed yet\n" );
  220.         // Remember that we want this url.
  221.         explicitURL = true;
  222.     }
  223.   }
  224.  
  225.   function onLoadViaOpenDialog() {
  226.     // See if load in progress (loading default page).
  227.     if ( document.getElementById("Browser:Throbber").getAttribute("busy") == "true" ) {
  228.         dump( "Stopping load of default initial page\n" );
  229.         appCore.stop();
  230.     }
  231.     dump( "Loading page specified via openDialog\n" );
  232.     dump("Check if a view source window \n");
  233.     if( window.arguments[1]=="view-source" )
  234.     {
  235.         dump(" A view source window \n");
  236.         var element = document.getElementById("main-window");
  237.         
  238.         var preface = element.getAttribute("viewsourcetitlepreface");
  239.         element.setAttribute( "titlepreface", preface );
  240.         appCore.isViewSource = true;
  241.         element.setAttribute("windowtype","Browser:view-source");
  242.     }
  243.     appCore.loadUrl( window.arguments[0] );
  244.   }
  245.  
  246.   function tryToSetContentWindow() {
  247.     var startpage = startPageDefault;
  248.     if ( window.content ) {
  249.         dump("Setting content window\n");
  250.         appCore.setContentWindow( window.content );
  251.         // Have browser app core load appropriate initial page.
  252.  
  253. /* sspitzer: I think this code is unnecessary, but I'll leave it until I prove it */
  254. /* START OF UNNECESSARY CODE */
  255.         if ( !explicitURL ) {
  256.             try {
  257.                 var handler = Components.classes['component://netscape/commandlinehandler/general-startup-browser'];
  258.                 handler = handler.getService();
  259.                 handler = handler.QueryInterface(Components.interfaces.nsICmdLineHandler);
  260.                 if (handler) {
  261.                     startpage = handler.defaultArgs;
  262.                 }
  263.             }
  264.             catch (ex) {
  265.                 dump("failed, reason: " + ex + "\n");
  266.                 startpage = startPageDefault;
  267.             }
  268.  
  269.             //dump("startpage = " + startpage + "\n");
  270.             var args = document.getElementById("args")
  271.             if (args) args.setAttribute("value", startpage);
  272.         }
  273. /* END OF UNNECESSARY CODE */
  274.  
  275.         appCore.loadInitialPage();
  276.     } else {
  277.         // Try again.
  278.         dump("Scheduling later attempt to set content window\n");
  279.         window.setTimeout( "tryToSetContentWindow()", 100 );
  280.     }
  281.   }
  282.  
  283.   function Translate()
  284.   {
  285.     var service = "http://cgi.netscape.com/cgi-bin/translate.cgi?AlisUI=simple_frames/ns_home";
  286.  
  287.     // if we're already viewing a translated page, then just get the
  288.     // last argument (which we expect to always be "AlisTargetURI")
  289.     var targetURI = window.content.location.href;
  290.     var targetURIIndex = targetURI.indexOf("AlisTargetURI=");
  291.     if (targetURIIndex >= 0)
  292.     {
  293.         targetURI = targetURI.substring(targetURIIndex + 14);
  294.     }
  295.     service += "&AlisTargetURI=" + targetURI;
  296.  
  297.     window.content.location.href = service;
  298.   }
  299.  
  300.   function RefreshUrlbar()
  301.   {
  302.    //Refresh the urlbar bar
  303.     document.getElementById('urlbar').value = window.content.location.href;
  304.   }
  305.  
  306.   function gotoHistoryIndex(index)
  307.   {
  308.      appCore.gotoHistoryIndex(index);
  309.   }
  310.  
  311.   function BrowserBack()
  312.   {
  313.      // Get a handle to the back-button
  314.      var bb = document.getElementById("canGoBack");
  315.      // If the button is disabled, don't bother calling in to Appcore
  316.      if ( (bb.getAttribute("disabled")) == "true" ) 
  317.         return;
  318.  
  319.     if (appCore != null) {
  320.       dump("Going Back\n");
  321.       appCore.back();
  322.     } else {
  323.       dump("BrowserAppCore has not been created!\n");
  324.     }
  325.   }
  326.  
  327.  
  328.   function BrowserForward()
  329.   {
  330.      // Get a handle to the back-button
  331.      var fb = document.getElementById("canGoForward");
  332.      // If the button is disabled, don't bother calling in to Appcore
  333.      if ( (fb.getAttribute("disabled")) == "true" ) 
  334.         return;
  335.  
  336.     if (appCore != null) {
  337.       dump("Going Forward\n");
  338.       appCore.forward();
  339.     } else {
  340.       dump("BrowserAppCore has not been created!\n");
  341.     }
  342.   }
  343.  
  344.  
  345.  
  346.   function BrowserCanStop() {
  347.     var stop = document.getElementById("canStop");
  348.     if ( stop ) {
  349.         var stopDisabled = stop.getAttribute("disabled");
  350.         var stopButton   = document.getElementById( "stop-button" );
  351.         if ( stopButton ) {
  352.             if ( stopDisabled == "true") {
  353.                 stopButton.setAttribute( "disabled", "true" );
  354.             } else {
  355.                 stopButton.setAttribute( "disabled", "" );
  356.             }
  357.         }
  358.         //Enable/disable the stop menu item
  359.         var stopMenu   = document.getElementById( "menuitem-stop" );
  360.         if ( stopMenu ) {
  361.             if ( stopDisabled == "true") {
  362.                 stopMenu.setAttribute( "disabled", "true" );
  363.             } else {
  364.                 stopMenu.setAttribute( "disabled", "" );
  365.             }
  366.         }
  367.     }
  368.   }
  369.  
  370.   function BrowserStop() {
  371.      // Get a handle to the "canStop" broadcast id
  372.      var stopBElem = document.getElementById("canStop");
  373.      if (!stopBElem) {
  374.         dump("Couldn't obtain handle to stop Broadcast element\n");
  375.         return;
  376.        }
  377.  
  378.      var canStop = stopBElem.getAttribute("disabled");
  379.      var sb = document.getElementById("stop-button");
  380.      
  381.      if (!sb) {
  382.           dump("Could not obtain handle to stop button\n");
  383.          return;
  384.      }
  385.  
  386.      // If the stop button is currently disabled, just return
  387.      if ((sb.getAttribute("disabled")) == "true") {
  388.         return;
  389.      }
  390.     
  391.      //Stop button has just been pressed. Disable it. 
  392.      sb.setAttribute("disabled", "true");
  393.  
  394.      // Get a handle to the stop menu item.
  395.      var sm = document.getElementById("menuitem-stop");
  396.      if (!sm) {
  397.        dump("Couldn't obtain menu item Stop\n");
  398.      } else {
  399.        // Disable the stop menu-item.
  400.        sm.setAttribute("disabled", "true");
  401.      }
  402.   
  403.      //Call in to BrowserAppcore to stop the current loading
  404.      if (appCore != null) {
  405.         dump("Going to Stop\n");
  406.         appCore.stop();
  407.      } else {
  408.         dump("BrowserAppCore has not been created!\n");
  409.      }
  410.   }
  411.  
  412.  
  413.   function BrowserReallyReload(reloadType) {
  414.      // Get a handle to the "canReload" broadcast id
  415.      var reloadBElem = document.getElementById("canReload");
  416.      if (!reloadBElem) {
  417.         dump("Couldn't obtain handle to reload Broadcast element\n");
  418.         return;
  419.        }
  420.  
  421.      var canreload = reloadBElem.getAttribute("disabled");
  422.      
  423.  
  424.      // If the reload button is currently disabled, just return
  425.      if ( canreload) {
  426.          return;
  427.      }
  428.     
  429.      //Call in to BrowserAppcore to reload the current loading
  430.      if (appCore != null) {
  431.         dump("Going to reload\n");
  432.         appCore.reload(reloadType);
  433.      } else {
  434.         dump("BrowserAppCore has not been created!\n");
  435.      }
  436.   }
  437.  
  438.   function BrowserHome()
  439.   {
  440.    // this eventual calls nsGlobalWIndow::Home()
  441.    window.content.home();
  442.    RefreshUrlbar();
  443.   }
  444.  
  445.   function OpenBookmarkURL(node, datasources)
  446.   {
  447.     if (node.getAttribute('container') == "true") {
  448.       return false;
  449.     }
  450.  
  451.     var url = node.getAttribute('id');
  452.     try
  453.     {
  454.         // add support for IE favorites under Win32, and NetPositive URLs under BeOS
  455.         var rdf = Components.classes["component://netscape/rdf/rdf-service"].getService();
  456.         if (rdf)   rdf = rdf.QueryInterface(Components.interfaces.nsIRDFService);
  457.         if (rdf && datasources)
  458.         {
  459.             var src = rdf.GetResource(url, true);
  460.             var prop = rdf.GetResource("http://home.netscape.com/NC-rdf#URL", true);
  461.             var target = datasources.GetTarget(src, prop, true);
  462.             if (target)    target = target.QueryInterface(Components.interfaces.nsIRDFLiteral);
  463.             if (target)    target = target.Value;
  464.             if (target)    url = target;
  465.         }
  466.     }
  467.     catch(ex)
  468.     {
  469.     }
  470.  
  471.     // Ignore "NC:" urls.
  472.     if (url.substring(0, 3) == "NC:") {
  473.       return false;
  474.     }
  475.     // Check if we have a browser window
  476.     if ( window.content == null )
  477.     {
  478.         window.openDialog( "chrome://navigator/content/navigator.xul", "_blank", "chrome,all,dialog=no", url ); 
  479.     }
  480.     else
  481.     {
  482.         window.content.location.href = url;
  483.         RefreshUrlbar();
  484.       }
  485.   }
  486.  
  487. function OpenSearch(tabName, forceDialogFlag, searchStr)
  488. {
  489.     var searchMode = 0;
  490.     var searchEngineURI = null;
  491.     var autoOpenSearchPanel = false;
  492.     var defaultSearchURL = null;
  493.     var fallbackDefaultSearchURL = "http://info.netscape.com/fwd/sidb1dnet/http://search.netscape.com/cgi-bin/search?search="
  494.     try
  495.     {
  496.         searchMode = pref.GetIntPref("browser.search.powermode");
  497.         autoOpenSearchPanel = pref.GetBoolPref("browser.search.opensidebarsearchpanel");
  498.         searchEngineURI = pref.CopyCharPref("browser.search.defaultengine");
  499.         defaultSearchURL = pref.CopyCharPref("browser.search.defaulturl");
  500.         
  501.     }
  502.     catch(ex)
  503.     {
  504.     }
  505.     dump("Search defaultSearchURL: " + defaultSearchURL + "\n");
  506.     if ((defaultSearchURL == null) || (defaultSearchURL == ""))
  507.     {
  508.         // Fallback to a Netscape default (one that we can get sidebar search results for)
  509.         defaultSearchURL = fallbackDefaultSearchURL;
  510.     }
  511.     dump("This is before the search " + window.content.location.href + "\n");
  512.     dump("This is before the search " + searchStr + "\n");
  513.     if ((window.content.location.href == searchStr) || (searchStr == '')) 
  514.     {
  515.         if (!(defaultSearchURL == fallbackDefaultSearchURL)) {
  516.             window.content.location.href = defaultSearchURL;
  517.         }
  518.         else
  519.         {
  520.             window.content.location.href = "http://info.netscape.com/fwd/6_0b1/http://search.netscape.com/"
  521.         }
  522.     }
  523.     else
  524.     {
  525.         if ((searchMode == 1) || (forceDialogFlag == true))
  526.         {
  527.             // Use a single search dialog
  528.             var cwindowManager = Components.classes["component://netscape/rdf/datasource?name=window-mediator"].getService();
  529.             var iwindowManager = Components.interfaces.nsIWindowMediator;
  530.             var windowManager  = cwindowManager.QueryInterface(iwindowManager);
  531.             var searchWindow = windowManager.getMostRecentWindow("search:window");
  532.             if (searchWindow)
  533.             {
  534.                 searchWindow.focus();
  535.                 if (searchWindow.loadPage)    searchWindow.loadPage(tabName, searchStr);
  536.             }
  537.             else
  538.             {
  539.                 window.openDialog("chrome://search/content/search.xul", "SearchWindow", "dialog=no,close,chrome,resizable", tabName, searchStr);
  540.             }
  541.         }
  542.         else 
  543.         {  
  544.             if ((!searchStr) || (searchStr == ""))    return;
  545.  
  546.             var searchDS = Components.classes["component://netscape/rdf/datasource?name=internetsearch"].getService();
  547.             if (searchDS)    searchDS = searchDS.QueryInterface(Components.interfaces.nsIInternetSearchService);
  548.  
  549.             var    escapedSearchStr = escape(searchStr);
  550.             defaultSearchURL += escapedSearchStr;
  551.  
  552.             if (searchDS)
  553.             {
  554.                 searchDS.RememberLastSearchText(escapedSearchStr);
  555.  
  556.                 if ((searchEngineURI != null) && (searchEngineURI != ""))
  557.                 {
  558.                     try
  559.                     {
  560.                         var    searchURL = searchDS.GetInternetSearchURL(searchEngineURI, escapedSearchStr);
  561.                         if ((searchURL != null) && (searchURL != ""))
  562.                         {
  563.                             defaultSearchURL = searchURL;
  564.                         }
  565.                     }
  566.                     catch(ex)
  567.                     {
  568.                     }
  569.                 }
  570.             }  
  571.             window.content.location.href = defaultSearchURL;
  572.         }
  573.     }
  574.  
  575.     // should we try and open up the sidebar to show the "Search Results" panel?
  576.     if (autoOpenSearchPanel == true)
  577.     {
  578.         RevealSearchPanel();
  579.     }
  580. }
  581.  
  582. function RevealSearchPanel()
  583. {
  584.     // rjc Note: the following is all a hack until the sidebar has appropriate APIs
  585.     // to check whether its shown/hidden, open/closed, and can show a particular panel
  586.  
  587.     var sidebar = document.getElementById("sidebar-box");
  588.     var sidebar_splitter = document.getElementById("sidebar-splitter");
  589.     var searchPanel = document.getElementById("urn:sidebar:panel:search");
  590.  
  591.     if (sidebar && sidebar_splitter && searchPanel)
  592.     {
  593.         var is_hidden = sidebar.getAttribute("hidden");
  594.         if (is_hidden && is_hidden == "true")
  595.         {
  596.             // SidebarShowHide() lives in sidebarOverlay.js
  597.             SidebarShowHide();
  598.         }
  599.         var splitter_state = sidebar_splitter.getAttribute("state");
  600.         if (splitter_state && splitter_state == "collapsed") {
  601.             sidebar_splitter.removeAttribute("state");
  602.         }
  603.         // SidebarSelectPanel() lives in sidebarOverlay.js
  604.         SidebarSelectPanel(searchPanel);
  605.     }
  606. }
  607.  
  608.   function BrowserNewWindow()
  609.   {
  610.     OpenBrowserWindow();
  611.   }
  612.  
  613.   function BrowserEditPage(url)
  614.   {
  615.     window.openDialog( "chrome://editor/content", "_blank", "chrome,all,dialog=no", url );
  616.   }
  617.  
  618. //Note: BrowserNewEditorWindow() was moved to globalOverlay.xul and renamed to NewEditorWindow()
  619.   
  620.   function BrowserOpenWindow()
  621.   {
  622.     //opens a window where users can select a web location to open
  623.     window.openDialog( "chrome://navigator/content/openLocation.xul", "_blank", "chrome,modal", appCore );
  624.   }
  625.   
  626.   /* Called from the openLocation dialog. This allows that dialog to instruct
  627.      its opener to open a new window and then step completely out of the way.
  628.      Anything less byzantine is causing horrible crashes on Linux. */
  629.   function delayedOpenWindow(chrome,flags,url) {
  630.     setTimeout("window.openDialog('"+chrome+"','_blank','"+flags+"','"+url+"')", 10);
  631.   }
  632.  
  633.   function createInstance( progid, iidName ) {
  634.       var iid = eval( "Components.interfaces." + iidName );
  635.       return Components.classes[ progid ].createInstance( iid );
  636.   }
  637.  
  638.   function createInstanceById( cid, iidName ) {
  639.       var iid = eval( "Components.interfaces." + iidName );
  640.       return Components.classesByID[ cid ].createInstance( iid );
  641.   }
  642.  
  643.   function getService( progid, iidName ) {
  644.       var iid = eval( "Components.interfaces." + iidName );
  645.       return Components.classes[ progid ].getService( iid );
  646.   }
  647.  
  648.   function getServiceById( cid, iidName ) {
  649.       var iid = eval( "Components.interfaces." + iidName );
  650.       return Components.classesByID[ cid ].getService( iid );
  651.   }
  652.  
  653.   function openNewWindowWith( url ) {
  654.     var newWin = window.openDialog( "chrome://navigator/content/navigator.xul", "_blank", "chrome,all,dialog=no", url );
  655.  
  656.     // Fix new window.    
  657.     newWin.saveFileAndPos = true;
  658.   }
  659.   
  660.   function BrowserOpenFileWindow()
  661.   {
  662.     // Get filespecwithui component.            
  663.     var fileSpec = createInstance( "component://netscape/filespecwithui", "nsIFileSpecWithUI" );
  664.     var url = null;
  665.     try {
  666.         fileSpec.parentWindow = window;
  667.         url = fileSpec.chooseFile( bundle.GetStringFromName( "openFile" ) );
  668.         fileSpec.parentWindow = null;
  669.     } catch ( exception ) {
  670.     }
  671.     if ( url && url != "" ) {
  672.         openNewWindowWith( url );
  673.     }
  674.   }
  675.  
  676.   function OpenFile(url) {
  677.     // Obsolete (called from C++ code that is no longer called).
  678.     dump( "OpenFile called?\n" );
  679.     openNewWindowWith( url );
  680.   }
  681.  
  682.   function BrowserCopy()
  683.   {
  684.     if (appCore != null) {
  685.         dump("Copying\n");
  686.       appCore.copy();
  687.     } else {
  688.       dump("BrowserAppCore has not been created!\n");
  689.     }
  690.   }
  691.  
  692.  
  693.   function BrowserAddBookmark(url,title)
  694.   {
  695.     var bmks = Components.classes["component://netscape/browser/bookmarks-service"].getService();
  696.     bmks = bmks.QueryInterface(Components.interfaces.nsIBookmarksService);
  697.     if ((title == null) || (title == ""))
  698.     {
  699.         title = url;
  700.     }
  701.     bmks.AddBookmark(url, title);
  702.   }
  703.  
  704. // Set up a lame hack to avoid opening two bookmarks.
  705. // Could otherwise happen with two Ctrl-B's in a row.
  706. var gDisableBookmarks = false;
  707. function enableBookmarks() {
  708.   gDisableBookmarks = false;
  709. }
  710.  
  711. function BrowserEditBookmarks()
  712.   // Use a single sidebar bookmarks dialog
  713.  
  714.   var cwindowManager = Components.classes['component://netscape/rdf/datasource?name=window-mediator'].getService();
  715.   var iwindowManager = Components.interfaces.nsIWindowMediator;
  716.   var windowManager  = cwindowManager.QueryInterface(iwindowManager);
  717.  
  718.   var bookmarksWindow = windowManager.getMostRecentWindow('bookmarks:manager');
  719.  
  720.   if (bookmarksWindow) {
  721.     //debug("Reuse existing bookmarks window");
  722.     bookmarksWindow.focus();
  723.   } else {
  724.     //debug("Open a new bookmarks dialog");
  725.  
  726.     if (true == gDisableBookmarks) {
  727.       //debug("Recently opened one. Wait a little bit.");
  728.       return;
  729.     }
  730.     gDisableBookmarks = true;
  731.  
  732.     window.open("chrome://bookmarks/content/", "_blank", "chrome,menubar,resizable,scrollbars");
  733.     setTimeout(enableBookmarks, 2000);
  734.   }
  735. }
  736.  
  737.   function BrowserPrintPreview()
  738.   {
  739.     // Borrowing this method to show how to 
  740.     // dynamically change icons
  741.     dump("BrowserPrintPreview\n");
  742.     if (appCore != null) {
  743.         dump("Changing Icons\n");
  744.       appCore.printPreview();
  745.     } else {
  746.       dump("BrowserAppCore has not been created!\n");
  747.     }
  748.   }
  749.  
  750.   function BrowserPrint()
  751.   {
  752.     // Borrowing this method to show how to 
  753.     // dynamically change icons
  754.     if (appCore != null) {
  755.       appCore.print();
  756.     }
  757.   }
  758.  
  759.   function BrowserSetDefaultCharacterSet(aCharset)
  760.   {
  761.     if (appCore != null) {
  762.       appCore.SetDocumentCharset(aCharset);
  763.       window.content.location.reload();
  764.     } else {
  765.       dump("BrowserAppCore has not been created!\n");
  766.     }
  767.   }
  768.  
  769.   function BrowserClose()
  770.   {
  771.     // This code replicates stuff in Shutdown().  It is here because
  772.     // window.screenX and window.screenY have real values.  We need
  773.     // to fix this eventually but by replicating the code here, we
  774.     // provide a means of saving position (it just requires that the
  775.     // user close the window via File->Close (vs. close box).
  776.  
  777.     // Get the current window position/size.
  778.     var x = window.screenX;
  779.     var y = window.screenY;
  780.     var h = window.outerHeight;
  781.     var w = window.outerWidth;
  782.  
  783.     // Store these into the window attributes (for persistence).
  784.     var win = document.getElementById( "main-window" );
  785.     win.setAttribute( "x", x );
  786.     win.setAttribute( "y", y );
  787.     win.setAttribute( "height", h );
  788.     win.setAttribute( "width", w );
  789.  
  790.        window.close();
  791.   }
  792.  
  793.  
  794.  
  795.   function BrowserSelectAll() {
  796.     if (appCore != null) {
  797.         appCore.selectAll();
  798.     } else {
  799.         dump("BrowserAppCore has not been created!\n");
  800.     }
  801.   }
  802.  
  803.   function BrowserFind() {
  804.     if (appCore != null) {
  805.         appCore.find();      
  806.     } else {
  807.         dump("BrowserAppCore has not been created!\n");
  808.     }
  809.   }
  810.  
  811.   function BrowserFindAgain() {
  812.     if (appCore != null) {
  813.         appCore.findNext();      
  814.     } else {
  815.         dump("BrowserAppCore has not been created!\n");
  816.     }
  817.   }
  818.  
  819.   function BrowserLoadURL()
  820.   {
  821.     if (appCore == null)
  822.     {
  823.         dump("BrowserAppCore has not been initialized\n");
  824.         return;
  825.     }
  826.  
  827.     // rjc: added support for URL shortcuts (3/30/1999)
  828.     try {
  829.       var bmks = Components.classes["component://netscape/browser/bookmarks-service"].getService();
  830.       bmks = bmks.QueryInterface(Components.interfaces.nsIBookmarksService);
  831.  
  832.       var shortcutURL = bmks.FindShortcut(document.getElementById('urlbar').value);
  833.  
  834.       dump("FindShortcut: in='" + document.getElementById('urlbar').value + "'  out='" + shortcutURL + "'\n");
  835.  
  836.       if ((shortcutURL != null) && (shortcutURL != "")) {
  837.         document.getElementById('urlbar').value = shortcutURL;
  838.       }
  839.     }
  840.     catch (ex) {
  841.       // stifle any exceptions so we're sure to load the URL.
  842.     }
  843.  
  844.     appCore.loadUrl(document.getElementById('urlbar').value);
  845.       
  846.   }
  847.  
  848.   function readFromClipboard()
  849.   {
  850.     // Get clipboard.
  851.     var clipboard = Components
  852.                       .classes["component://netscape/widget/clipboard"]
  853.                         .getService ( Components.interfaces.nsIClipboard );
  854.     // Create tranferable that will transfer the text.
  855.     var trans = Components
  856.                    .classes["component://netscape/widget/transferable"]
  857.                      .createInstance( Components.interfaces.nsITransferable );
  858.     if ( !clipboard || !trans )
  859.       return;
  860.  
  861.     trans.addDataFlavor( "text/unicode" );
  862.     clipboard.getData(trans);
  863.  
  864.     var data = new Object();
  865.     var dataLen = new Object();
  866.     trans.getTransferData("text/unicode", data, dataLen);
  867.     var url = null;
  868.     if (data)
  869.     {
  870.       data = data.value.QueryInterface(Components.interfaces
  871.                                                     .nsISupportsWString);
  872.       url = data.data.substring(0, dataLen.value / 2);
  873.     }
  874.     return url;
  875.   }
  876.  
  877.   function browserLoadClipboardURL(target)
  878.   {
  879.     if (!((target.tagName.toUpperCase() == "INPUT"
  880.            && (target.type == "" || target.type.toUpperCase() == "TEXT"))
  881.           || target.tagName.toUpperCase() == "TEXTAREA"))
  882.     {
  883.       var url = readFromClipboard();
  884.       dump ("URL on clipboard: '" + url + "'; length = " + url.length + "\n");
  885.       if (url.length > 0)
  886.       {
  887.         var urlBar = document.getElementById("urlbar");
  888.         urlBar.value = url;
  889.         BrowserLoadURL();
  890.       }
  891.     }
  892.   }
  893.  
  894.   function OpenMessenger()
  895.   {
  896.     window.open("chrome://messenger/content/", "_blank", "chrome,menubar,toolbar,resizable");
  897.   }
  898.  
  899.   function OpenAddressbook()
  900.   {
  901.     window.open("chrome://addressbook/content/", "_blank", "chrome,menubar,toolbar,resizable");
  902.   }
  903.  
  904.   function BrowserSendLink(pageUrl, pageTitle)
  905.   {
  906.     window.openDialog( "chrome://messengercompose/content/", "_blank", 
  907.                        "chrome,all,dialog=no",
  908.                        "body='" + pageUrl + "',subject='" + pageTitle +
  909.                        "',bodyislink=true");
  910.   }
  911.  
  912.   function BrowserSendPage(pageUrl, pageTitle)
  913.   {
  914.     window.openDialog( "chrome://messengercompose/content/", "_blank", 
  915.                        "chrome,all,dialog=no", 
  916.                        "attachment='" + pageUrl + "',body='" + pageUrl +
  917.                        "',subject='" + pageTitle + "',bodyislink=true");
  918.   }
  919.  
  920.   function BrowserViewSource()
  921.   {
  922.     dump("BrowserViewSource(); \n ");
  923.     // Use a browser window to view source
  924.     window.openDialog( "chrome://navigator/content/",
  925.                        "_blank",
  926.                        "chrome,menubar,status,dialog=no,resizable",
  927.                        window.content.location,
  928.                        "view-source" );
  929.   }
  930.  
  931.  
  932.         var bindCount = 0;
  933.         function onStatus() {
  934.             var status = document.getElementById("Browser:Status");
  935.             if ( status ) {
  936.                 var text = status.getAttribute("value");
  937.                 if ( text == "" ) {
  938. //dump( "Setting default status text\n" );                    
  939.                     text = defaultStatus;
  940.                 }
  941.                 var statusText = document.getElementById("statusText");
  942.                 if ( statusText ) {
  943. //dump( "Setting status text: " + text + "\n" );
  944.                     statusText.setAttribute( "value", text );
  945.                 } else {
  946. //dump( "Missing statusText when setting status text: " + text + "\n" );
  947.                 }
  948.             } else {
  949.                 dump("Can't find status broadcaster!\n");
  950.             }
  951.         }
  952.  
  953.         function doTests() {
  954.         }
  955.  
  956.         var startTime = 0;
  957.         function onProgress() {
  958.             var throbber = document.getElementById("Browser:Throbber");
  959.             var meter    = document.getElementById("Browser:LoadingProgress");
  960.             if ( throbber && meter ) {
  961.                 var busy = throbber.getAttribute("busy");
  962.                 var wasBusy = meter.getAttribute("mode") == "undetermined" ? "true" : "false";
  963.                 if ( busy == "true" ) {
  964.                     if ( wasBusy == "false" ) {
  965.                         // Remember when loading commenced.
  966.                         startTime = (new Date()).getTime();
  967.                         // Turn progress meter on.
  968.                         meter.setAttribute("mode","undetermined");
  969.                     }
  970.                     // Update status bar.
  971.                 } else if ( busy == "false" && wasBusy == "true" ) {
  972.                     // Record page loading time.
  973.                     var status = document.getElementById("Browser:Status");
  974.                     if ( status ) {
  975.                         var elapsed = ( (new Date()).getTime() - startTime ) / 1000;
  976.                         var msg = bundle.GetStringFromName("nv_done") + " (" + elapsed + " secs)";
  977.                         dump( msg + "\n" );
  978.                         status.setAttribute("value",msg);
  979.                         defaultStatus = msg;
  980.                     }
  981.                     // Turn progress meter off.
  982.                     meter.setAttribute("mode","normal");
  983.                 }
  984.             }
  985.         }
  986.         function dumpProgress() {
  987.             var broadcaster = document.getElementById("Browser:LoadingProgress");
  988.             var meter       = document.getElementById("meter");
  989.             dump( "bindCount=" + bindCount + "\n" );
  990.             dump( "broadcaster mode=" + broadcaster.getAttribute("mode") + "\n" );
  991.             dump( "broadcaster value=" + broadcaster.getAttribute("value") + "\n" );
  992.             dump( "meter mode=" + meter.getAttribute("mode") + "\n" );
  993.             dump( "meter value=" + meter.getAttribute("value") + "\n" );
  994.         }
  995.  
  996. function BrowserReload() {
  997.     dump( "Sorry, command not implemented.\n" );
  998. }
  999.  
  1000. function hiddenWindowStartup()
  1001. {
  1002.     // Disable menus which are not appropriate
  1003.     var disabledItems = ['cmd_close', 'Browser:SendPage', 'Browser:EditPage', 'Browser:PrintSetup', 'Browser:PrintPreview',
  1004.                          'Browser:Print', 'canGoBack', 'canGoForward', 'Browser:Home', 'Browser:AddBookmark', 'cmd_undo', 
  1005.                          'cmd_redo', 'cmd_cut', 'cmd_copy','cmd_paste', 'cmd_delete', 'cmd_selectAll'];
  1006.     for ( id in disabledItems )
  1007.     {
  1008.          // dump("disabling "+disabledItems[id]+"\n");
  1009.          var broadcaster = document.getElementById( disabledItems[id]);
  1010.          if (broadcaster)
  1011.            broadcaster.setAttribute("disabled","true");
  1012.     }
  1013. }
  1014.  
  1015. // Tile
  1016. function TileWindow()
  1017. {
  1018.     var xShift = 25;
  1019.     var yShift = 50;
  1020.     var done = false;
  1021.     var windowManager = Components.classes['component://netscape/rdf/datasource?name=window-mediator'].getService();
  1022.     dump("got window Manager \n");
  1023.     var    windowManagerInterface = windowManager.QueryInterface( Components.interfaces.nsIWindowMediator);
  1024.     
  1025.     var enumerator = windowManagerInterface.getEnumerator( null );
  1026.     
  1027.     var xOffset = screen.availLeft;
  1028.     var yOffset = screen.availRight;
  1029.     do
  1030.     {
  1031.         var currentWindow = windowManagerInterface.convertISupportsToDOMWindow ( enumerator.GetNext() );
  1032.         if ( currentWindow.screenX == screenX && currentWindow.screenY == screenY )
  1033.         {
  1034.             alreadyThere = true;
  1035.             break;
  1036.         }    
  1037.     } while ( enumerator.HasMoreElements() )
  1038.     
  1039.     if ( alreadyThere )
  1040.     {
  1041.         enumerator = windowManagerInterface.getEnumerator( null );
  1042.         do
  1043.         {
  1044.             var currentWindow = windowManagerInterface.convertISupportsToDOMWindow ( enumerator.GetNext() );
  1045.             if ( currentWindow.screenX == screenX+xOffset*xShift+yOffset*xShift   && currentWindow.screenY == screenY+yShift*xOffset && window != currentWindow )
  1046.             {
  1047.                 xOffset++;
  1048.                 if ( (screenY+outerHeight  < screen.availHeight) && (screenY+outerHeight+yShift*xOffset > screen.availHeight ) )
  1049.                 {
  1050.                     dump(" increment yOffset");
  1051.                     yOffset++;
  1052.                     xOffset = 0;
  1053.                 }
  1054.                 enumerator = windowManagerInterface.getEnumerator( null );
  1055.             }    
  1056.         } while ( enumerator.HasMoreElements() )
  1057.     }
  1058.     
  1059.     if ( xOffset > 0 || yOffset >0 )
  1060.     {
  1061.         dump( "offsets:"+xOffset+" "+yOffset+"\n");
  1062.         dump("Move by ("+ xOffset*xShift + yOffset*xShift +","+ yShift*xOffset +")\n");
  1063.         moveBy( xOffset*xShift + yOffset*xShift, yShift*xOffset );
  1064.     }
  1065. }
  1066. // Make sure that a window fits fully on the screen. Will move to preserve size, and then shrink to fit
  1067. function FitToScreen()
  1068. {
  1069.     var moveX = screenX;
  1070.     var sizeX = outerWidth;
  1071.     var moveY = screenY;
  1072.     var sizeY = outerHeight;
  1073.     
  1074.     dump( " move to ("+moveX+","+moveY+") size to ("+sizeX+","+sizeY+") \n");
  1075.     var totalWidth = screenX+outerWidth;
  1076.     if ( totalWidth > screen.availWidth )
  1077.     {    
  1078.         if( outerWidth > screen.availWidth )
  1079.         {
  1080.             sizeX = screen.availWidth;
  1081.             moveX = screen.availLeft;
  1082.         }
  1083.         else
  1084.         {
  1085.             moveX = screen.availWidth- outerWidth;
  1086.         }
  1087.     }
  1088.     
  1089.     var totalHeight = screenY+outerHeight;
  1090.     if ( totalHeight > screen.availHeight )
  1091.     {    
  1092.         if( outerWidth > screen.availHeight )
  1093.         {
  1094.             sizeY = screen.availHeight;
  1095.             moveY = screen.availTop;
  1096.         }
  1097.         else
  1098.         {
  1099.             moveY = screen.availHeight- outerHeight;
  1100.         }
  1101.     }
  1102.     
  1103.     
  1104.     dump( " move to ("+moveX+","+moveY+") size to ("+sizeX+","+sizeY+") \n");
  1105.     if ( (moveY- screenY != 0 ) ||    (moveX-screenX != 0 ) )
  1106.         moveTo( moveX,moveY );
  1107.     
  1108.     // Maintain a minimum size
  1109.     if ( sizeY< 100 )
  1110.         sizeY = 100;
  1111.     if ( sizeX < 100 )
  1112.         sizeX = 100; 
  1113.     if ( (sizeY- outerHeight != 0 ) ||    (sizeX-outerWidth != 0 ) )
  1114.     {
  1115.         //outerHeight = sizeY;
  1116.         //outerWidth = sizeX;
  1117.         resizeTo( sizeX,sizeY );    
  1118.     }
  1119. }
  1120.  
  1121. // Dumps all properties of anObject.
  1122. function dumpObject( anObject, prefix ) {
  1123.     if ( prefix == null ) {
  1124.         prefix = anObject;
  1125.     }
  1126.     for ( prop in anObject ) {
  1127.         dump( prefix + "." + prop + " = " + anObject[prop] + "\n" );
  1128.     }
  1129. }
  1130.  
  1131. // Takes JS expression and dumps "expr="+expr+"\n"
  1132. function dumpExpr( expr ) {
  1133.     dump( expr+"="+eval(expr)+"\n" );
  1134. }
  1135.  
  1136. var leakDetector = null;
  1137.  
  1138. // Dumps current set of memory leaks.
  1139. function dumpMemoryLeaks() {
  1140.     if (leakDetector == null)
  1141.         leakDetector = createInstance("component://netscape/xpcom/leakdetector", "nsILeakDetector");
  1142.     if (leakDetector != null)
  1143.         leakDetector.dumpLeaks();
  1144. }
  1145.